<?php session_start(); ?>

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <title>发表博文</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="./css/simditor.css" />
    <link rel="stylesheet" type="text/css" href="./css/layui.css" />
    <script type="text/javascript" src="./js/jquery.min.js"></script>
    <script type="text/javascript" src="./js/module.js"></script>
    <script type="text/javascript" src="./js/hotkeys.js"></script>
    <script type="text/javascript" src="./js/uploader.js"></script>
    <script type="text/javascript" src="./js/simditor.js"></script>
    <script type="text/javascript" src="./js/layui.js"></script>
    <style>
        .editor-main{
            width: 80%;
            margin: 10px auto;
        }
        .icon>img{
            width:300px;
            height:200px;
            border: 1px #c9d8db solid;
            margin-left: 20px;
        }
        #uploadImage{
            float:left;
        }
        .btn-group{
            text-align:center;
        }
        #target-group{
            display:inline-block;
            line-height:35px;
        }
        .target{
            display:inline-block;
            margin:0 8px;
            position: relative;
        }
        .target>ins{
            position: absolute;
            top: -14px;
            right: -5px;
            cursor: pointer;
            text-decoration: none;
        }
    </style>
</head>
<body>
	<div class="editor-main layui-form layui-form-pane">
        <input type="hidden" id='user_id' value = <?php echo $_SESSION['m_id'] ?> />
        <div class="layui-form-item">
            <label class="layui-form-label">博客标题：</label>
            <div class="layui-input-block">
                <input type="text" id='title' placeholder="请输入博客标题" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item layui-form-text">
            <label class="layui-form-label">博客简介：</label>
            <div class="layui-input-block">
                <textarea id='outline' placeholder="请输入博客简介" class="layui-textarea"></textarea>
            </div>
        </div>
        <div class="layui-form-item layui-form-text">
            <label class="layui-form-label">内容：</label>
            <div class="layui-input-block">
                <textarea id="editor" autofocus></textarea>
            </div>
        </div>
        <div class="layui-form-item ">
            <label class="layui-form-label">文章头像：</label>
            <div class="layui-input-block icon">
                <button type="button" class="layui-btn" id="uploadImage" >
                    <i class="layui-icon">&#xe67c;</i><span>上传图片</span>
                </button>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">文章标签：</label>
            <div class="layui-input-inline">
                <input id="addTar" type="text" lay-verify="required" placeholder="请输入标签，最多5个" autocomplete="off" class="layui-input">
            </div>
            <div id="target-group"></div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">文章类型：</label>
            <div class="layui-input-inline">
                <select id="type-group">
                    <option value="" selected="" >请选择文章标签</option>
                </select>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">文章权限：</label>
            <div class="layui-input-inline">
                <input id="blog_state" type="checkbox" lay-skin="switch" lay-text="公开|私密" checked />
            </div>
        </div>
        <div class="btn-group">
            <input type="button" id="btnPublish" class="layui-btn" value="发表博客"/>
            <input type="button" id="btnback" class="layui-btn layui-btn-primary" value="返回"/>
        </div>
	</div>
<script>
    //删除节点
    function delTarget(tar){
        document.getElementById("target-group").removeChild(tar.parentNode);        //删除标签
    }
</script>

<script>
    $(function(){
        //添加标签节点
        $('#addTar').keypress(function(e){          //监听标签框输入回车
            var flag = true;
            var data = this.value.trim();
            var res = /^[\u4e00-\u9fa5_a-zA-Z]+$/;       //字母
            if(e.which == 13 && data != ''){
                if(res.test(data)){
                    for(var i=0;i<$(".target").find("span").length;i++){            //判断是否重复
                        if(data == $($(".target").find("span")[i]).text()){
                            this.value = '';
                            flag = false;
                            return; 
                        }
                    }
                    if(data.length>10){
                        layer.msg('标签长度不能超过10',{icon: 5,anim:6, time: 2000});
                    }else{
                        if($(".target").length<5){
                            $("#target-group").append('<div class="target"><span class="layui-btn layui-btn-sm layui-btn-radius layui-btn-normal">'+data+'</span><ins onclick="delTarget(this)">×</ins></div>');
                            this.value = '';
                        }else{
                            layer.msg('一篇文章最多能有5个标签哦',{icon:7 ,anim:6, time: 2000}); 
                        }
                    }
                }else{
                    layer.msg('请输入汉字或字符',{icon: 5,anim:6, time: 2000}); 
                }
            }
        })
        //调用上传文件
        layui.use(['upload','form'], function(){
            var upload = layui.upload;
            var form = layui.form;
            //执行实例
            var uploadInst = upload.render({
                elem: '#uploadImage' //绑定元素
                ,url: '/blog_system/admin/view/action/upload.php?type=b_tx' //上传接口
                ,size: 2048 // 设置图片大小，单位 KB
                ,done: function(data){
                    console.log(data);
                    if(data.code == 200){
                        if($(".icon img").length==0){              //判断是否需要新加节点
                            $(".icon").append("<img src="+data.file_path+" alt='文章头像' />");
                            $("#uploadImage>span").html('重新上传');
                        }else{
                            $(".icon img").attr('src',data.file_path);
                        }
                    }else {
                        layer.msg(data.msg,{icon: 5,anim:6, time: 2000}); 
                    }
                }
                ,error: function(){
                    layer.msg('服务器错误，请稍后重试',{icon: 5,anim:6, time: 2000}); 
                }
            });
        });
        //初始化 Simditor 插件
        Simditor.locale = 'zh-CN';//设置中文
        var editor = new Simditor({
            textarea: $('#editor'),  
            placeholder: '这里输入文字...',
            toolbar:  ['title', 'bold', 'italic', 'underline', 'strikethrough', 'fontScale', 'color', '|', 'ol', 'ul', 'blockquote', 'code', 'table', '|', 'link', 'image', 'hr', '|', 'indent', 'outdent', 'alignment'], //工具条都包含哪些内容
            pasteImage: true,//允许粘贴图片
            //defaultImage: '/res/simditor/images/image.png', //编辑器插入的默认图片
            upload : {
                url : '/blog_system/admin/view/action/upload.php?type=sc', //文件上传的接口地址
                params: null, //键值对,指定文件上传接口的额外参数,上传的时候随文件一起提交
                fileKey: 'upload_file', //服务器端获取文件数据的参数名
                connectionCount: 1,
                leaveConfirm: '正在上传, 你确定要离开吗?'
            }
        });
        editor.uploader.on('uploadsuccess', (res,file,mask)=>{
            //获得上传的文件对象
            let img = file.img;
            console.log(file);//simditor的文件对象
            console.log(mask);//返回的数据
            var data = JSON.parse(mask); //转换为JSON对象
            if(data.code == 200){
                img.attr('src',data.file_path);//重新给img标签的src属性赋值图片路径
            }else {
                layer.msg('操作失败',{icon: 5,anim:6, time: 2000}); 
            }
        });
        //请求文章类型
        $.ajax({
            async:true,     //异步请求
            url:'/blog_system/admin/index.php/Type/getTypesJson?state=normal',
            type:'POST',
            contentType: "application/x-www-form-urlencoded;charset=utf-8",
            success:function(result){
                var data = JSON.parse(result).data;
                var len = data.length;
                for(var i=0;i<len;i++){
                    $("#type-group").append('<option value='+data[i].id+'>'+data[i].name+'</option>');
                }
            }
        })
        //点击发表博客按钮触发
        $("#btnPublish").click(function(){
            var title = $("#title").val().trim();
            var outline = $("#outline").val().trim();
            var content = editor.getValue();
            var icon = $(".icon img").attr('src');
            var target_len =  $(".target").find("span").length;
            var type = $("#type-group").val();
            var state = $("#blog_state").prop("checked")?1:0;
            var user_id = $('#user_id').val();
            if(title==''){
                layer.msg('博客标题不能为空',{icon: 5,anim:6, time: 2000});
                return ;
            }else if(title.length>60){
                layer.msg('博客标题过长（60字以内）',{icon: 5,anim:6, time: 2000}); 
                return ;
            }else if(outline==''){
                layer.msg('博客简介不能为空',{icon: 5,anim:6, time: 2000}); 
                return ;
            }else if(outline.length>400){
                layer.msg('博客简介过长（200字以内）',{icon: 5,anim:6, time: 2000}); 
                return ;
            }else if(content==''){
                layer.msg('博客内容不能为空',{icon: 5,anim:6, time: 2000}); 
                return ;
            }else if(content.length>4000){
                layer.msg('博客内容过长了吧，精简点~',{icon: 5,anim:6, time: 2000}); 
                return ;
            }else if(!icon){
                layer.msg('请上传文章图片',{icon: 5,anim:6, time: 2000}); 
                return ;
            }else if(target_len<1){
                layer.msg('请输入文章标签（最少1个，最多5个）',{icon: 5,anim:6, time: 2000}); 
                return ;
            }else if(type==''){
                layer.msg('请选择文章类型',{icon: 5,anim:6, time: 2000}); 
                return ;
            }else{
                //获取所有文章标签，并将他们存起来
                var target_data = new Array();  
                for(var i=0;i<$(".target").find("span").length;i++){           
                    target_data[i] = $($(".target").find("span")[i]).text();
                }
                //调用控制层的方法，并将数据传过去
                datainfo={
                    title:title,
                    outline:outline,
                    content:content,
                    blog_img:icon,
                    blog_type:type,
                    state:state,
                    target:target_data,
                    user_id:user_id
                }
                $.ajax({
                    async:true,
                    url:'/blog_system/admin/index.php/Blog/publishBlog',
                    type:'POST',
                    contentType: "application/x-www-form-urlencoded;charset=utf-8",
                    // dataType: "JSON",
                    data:datainfo,
                    success:function(result){
                        var data = JSON.parse(result);
                        console.log(data);
                        if(!data.id){
                            layer.msg('发表失败，请重新尝试"',{icon: 5,anim:6, time: 2000}); 
                            return;
                        }
                        window.location.href = "http://localhost:8888/blog_system/admin/view/publishInfo.php?type=1&id="+data.id;
                    }
                });
            }
        });
        //返回按钮
        $('#btnback').click(function(){
            history.go(-1);     //返回上一页
        });
    });
</script>
</html>


